package com.mby.controller;

import com.alibaba.fastjson.JSONObject;
import com.mby.entity.User;
import com.mby.entity.YyUser;
import com.mby.utils.*;
import net.dongliu.requests.Header;
import net.dongliu.requests.Requests;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

/**
 * Created by noah on 2018/4/15.
 */
@RestController
public class SessionController extends BaseController{

    /**
     * 登录
     * post /live/sessions
     * @param params(username,password)
     */
    @PostMapping(value = "/sessions", produces = "application/json; charset=UTF-8")
    public void login(@RequestBody JSONObject params) throws Exception{
        String tokeName;
        if(isMoblie){
            tokeName = "tokenM";
        }else{
            tokeName = "tokenP";
        }
        if(!params.getString("username").toLowerCase().substring(0,3).equals("mby")){
            JSONObject userInfo = Requests.post(WebConstant.DMS_LOGIN_URL)
                    .headers(new Header("content-type","application/json"))
                    .verify(false)
                    .body(params.toString())
                    .send().readToJson(JSONObject.class);
            if(userInfo.containsKey("userId")){
                YyUser yyUser = userInfo.toJavaObject(YyUser.class);
                User user = yyUser.toUser();
                if(StringUtils.isNotEmpty(user.getRoleName()) && StringUtils.isNotEmpty(user.getRoleIds())){
                    user.setLoginName(params.getString("username"));
                    String token = SecurityUtil.generate(user.getLoginName() + System.currentTimeMillis());
                    String rongCloudToken = loginRongCloud(user.getId().toString(),user.getUserName()+"（"+user.getRoleName().split(",")[0]+"）","http://live-asset.themobiyun.com/userIcon/"+user.getId().toString()+"?"+new Date().getTime()+"");
                    user.setRongCloudToken(rongCloudToken);
                    user = mongoTool.findAndUpdate("{'status':0,'rongCloudToken':'"+rongCloudToken+"','"+tokeName+"':'"+token+"','dealerId':'"+user.getDealerId()+"','loginName':'"+user.getLoginName().toLowerCase()+"','phone':'"+user.getPhone()+"','roleName':'"+UserUtil.filterRoleNames(user.getRoleName())+"','quited':"+user.getQuited()+",'roleIds':'"+ UserUtil.filterRoleIds(user.getRoleIds())+"'}","{'id':"+user.getId()+"}",User.class);
                    user.setDealerName(CsAppUtil.getDealer(user.getDealerId()).getName());
                    Subject subject = SecurityUtils.getSubject();
                    subject.getSession().setAttribute("currentUser", user);
                    respDataWithToken(user,token);
                }else{
                    respErr("User Needs Roles");
                }
            }else{
                if(userInfo.getString("errorMsg").contains("密码错误")){
                    respErr("Incorrect Password");
                }else if(userInfo.getString("errorMsg").contains("账号被锁定") || userInfo.getString("errorMsg").contains("账号已锁定")){
                    respErr("User Locked For 5mins");
                }else{
                    respErr("Dms Login Fail");
                }
            }
        }else{
            User tempUser = mongoTool.findOne("","{'loginName':'"+params.getString("username").toLowerCase()+"'}",User.class);
            if(tempUser != null){
                if(SecurityHelper.verify(params.getString("password"),tempUser.getPassword())){
                    String token = SecurityUtil.generate(tempUser.getLoginName() + System.currentTimeMillis());
                    tempUser = mongoTool.findAndUpdate("{'"+tokeName+"':'"+token+"'}","{'id':"+tempUser.getId()+"}",User.class);
                    Subject subject = SecurityUtils.getSubject();
                    subject.getSession().setAttribute("currentUser", tempUser);
                    respDataWithToken(tempUser,token);
                }else{
                    respErr("Incorrect Password");
                }
            }else{
                respErr("Nonexistent User");
            }
        }
    }

    /**
     * 登出
     * delete /live/sessions
     */
    @DeleteMapping(value = "/sessions")
    public void logout(){
        User tempUser;
        String tokeName;
        if(isMoblie){
            tokeName = "tokenM";
        }else{
            tokeName = "tokenP";
        }
        tempUser = mongoTool.findOne("id","{'"+tokeName+"':'"+token+"'}",User.class);
        if(tempUser != null){
            mongoTool.update("{'status':2,'"+tokeName+"':null}","{'id':"+tempUser.getId()+"}",User.class);
        }else{
            respErr("Login Required");
        }
        respDataWithToken(null,"#");
    }
}
